<template>
  <l-map :zoom=10 :center="initialLocation" :style="mapWindowStyle">
    <l-tile-layer :url="url"></l-tile-layer>
    <l-marker-cluster :options="clusterOptions" @clusterclick="click()" @ready="ready">
      <l-marker v-for="l in locations" :key="l.id" :lat-lng="l.latlng" :icon="icon">
        <l-popup :content="l.text"></l-popup>
      </l-marker>
    </l-marker-cluster>
  </l-map>
</template>

<script>
import {
  LMap,
  LTileLayer,
  LMarker,
  LPopup,
} from 'wgis.leaflet.vue2';// import * as Vue2Leaflet from 'vue2-leaflet'
import L, { latLng } from 'leaflet'
import Vue2LeafletMarkerCluster from 'vue2-leaflet-markercluster'
import path from "path";
const IMAGE_PATH = '/static/images'
L.Icon.Default.imagePath = IMAGE_PATH + '/'
const MARKER_ICON_URL = path.join(IMAGE_PATH, 'marker-icon.png')
const MARKER_SHADOW_URL = path.join(IMAGE_PATH, 'marker-shadow.png')

function rand(n) {
  // let max = n + 0.0625
  let min = n - 0.0625
  return Math.random() * 0.125 + min;
}

export default {
  components: {
    LMap,
    LTileLayer,
    LMarker,
    LPopup,
    'l-marker-cluster': Vue2LeafletMarkerCluster,
  },
  data () {
    const url = 'http://{s}.tile.osm.org/{z}/{x}/{y}.png'
    let locations = []
    for (let i = 0; i < 100; i++) {
      locations.push({
        id: i,
        latlng: latLng(rand(-34.9205), rand(-57.953646)),
        text: 'Hola ' + i
      })
    }
    let MyCustomMarker = L.Icon.extend({
      options: {
        shadowUrl: MARKER_SHADOW_URL,
        iconUrl: MARKER_ICON_URL,
        iconSize:     [25, 41], // size of the icon
        shadowSize:   [41, 41], // size of the shadow
        iconAnchor:   [13, 42], // point of the icon which will correspond to marker's location
        shadowAnchor: [13, 42], // the same for the shadow
        popupAnchor:  [0, -33], // point from which the popup should open relative to the iconAnchor
      },
    })

    return {
      url,
      locations,
      icon: new MyCustomMarker(),
      clusterOptions: {},
      initialLocation: latLng(-34.9205, -57.953646),
      mapWindowStyle: {
        height: '0'
      }
    }
  },
  created(){
    window.addEventListener('resize', this.getHeight);
    this.getHeight()
  },
  methods: {
    getHeight() {
      this.mapWindowStyle.height = String(window.innerHeight - 40) + 'px';
    },
    click: (e) => console.log("clusterclick", e),
    ready: (e) => console.log('ready', e),
  },
  mounted() {
    setTimeout(() => {
      // console.log('done')
      this.$nextTick(() =>{
        this.clusterOptions = { disableClusteringAtZoom: 11 }
      });
    }, 5000);
  }
}
</script>

<style lang="stylus">
@import "leaflet/dist/leaflet.css";
@import "leaflet.markercluster/dist/MarkerCluster.css";
@import "leaflet.markercluster/dist/MarkerCluster.Default.css";
</style>
